#include "client_manager.h"
#include <QTimer>
#include <QDebug>
#include <QThread>
#include <QNetworkInterface>

ClientManager::ClientManager(QObject *parent):
    QObject(parent)
{

    pCamera = new Camera(this);
    pCamera->CameraInit();
    client = new Client(pCamera);

    pThread = new QThread();
    pThread->start();
    client->moveToThread(pThread);
    client->InitTimer();

    bool res;
    client->Connect(getServerIp(), 9999, res);
    connect(pThread, &QThread::finished, client, &Client::deleteLater);
//    connect(client,&Client::sendListAdd,pCamera,&Camera::getListAdd);
}

ClientManager::~ClientManager()
{
    client->CloseTimer();
    client->CloseSocket();
    pThread->quit();
    pThread->wait();
    delete pThread;
//    delete client;
//    delete pCamera;
    //    pCamera = nullptr;
}

QString ClientManager::getServerIp()
{
    QList<QHostAddress> AddressList = QNetworkInterface::allAddresses();
      QHostAddress result;
      foreach(QHostAddress address, AddressList){
          if(address.protocol() == QAbstractSocket::IPv4Protocol &&
             address != QHostAddress::Null &&
             address != QHostAddress::LocalHost){
              if (address.toString().contains("127.0.")){
                continue;
              }
              result = address;
              break;
          }
      }
      QString Ip = result.toString();
      QStringList list1 = Ip.split(".");
      list1.last() = "100";
      Ip = "";
      for(int i = 0 ; i < list1.size() - 1; i++){
          Ip += (list1.at(i) + ".");
      }
      Ip +=list1.last();
      return Ip;
}

void ClientManager::closeOutput()
{
//    qDebug()<< "8888888888888";
    pCamera->releaseMemory();
    client->CloseTimer();
    client->CloseSocket();
//    pThread->quit();
//    pThread->wait();
//    delete pThread;
    qApp->quit();
}

